package com.kaka.bus.engine.evaluate;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.kaka.bus.AppCenter;
import com.kaka.bus.R;
import com.kaka.bus.adapter.EvaluateAdapter;
import com.kaka.bus.base.BaseActivity;
import com.kaka.bus.bean.EvaluateBean;
import com.kaka.bus.bean.HttpWrapper;
import com.kaka.bus.constant.Constant;
import com.kaka.bus.engine.evaluate.sell.SellActivity;
import com.kaka.bus.listener.Listener;
import com.kaka.bus.util.U;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Created by OnionMac on 2018/1/16.
 */

public class EvaluateActivity extends BaseActivity<EvaluatePresenter> implements EvaluateContract.View {



    @BindView(R.id.toolbar_back)
    ImageView mToolbarBack;
    @BindView(R.id.toolbar_name)
    TextView mToolbarName;
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.evaluate_recy)
    RecyclerView mEvaluateRecy;
    @BindView(R.id.evalaute_nest)
    NestedScrollView mEvalauteNest;
    @BindView(R.id.evaluate_btn_commit)
    AppCompatButton mEvaluateBtnCommit;
    @BindView(R.id.evaluate_serialnumber)
    TextView mEvaluateSerialnumber;
    @BindView(R.id.evaluate_tips)
    TextView mEvaluateTips;
    private LinearLayoutManager mLayoutManager;

    private List<EvaluateBean> mData = new ArrayList<>();
    private EvaluateAdapter mEvaluateAdapter;
    private int mNoPosition;
    private RxPermissions mRxPermissions;

    private String mJson;
    private String mSerialNumber;

    @Override
    protected void initView() {
        super.initView();
        mToolbarName.setText("检测评估");
        mToolbarBack.setOnClickListener(v -> finish());
        String model = U.getModel();
        mEvaluateTips.setText(U.connectString("您的手机为",model,",请如实评估一下选项,审核过之后急速放款。"));
        mLayoutManager = new LinearLayoutManager(this);
        mLayoutManager.setSmoothScrollbarEnabled(true);
        mLayoutManager.setAutoMeasureEnabled(true);
        mEvaluateRecy.setLayoutManager(mLayoutManager);
        mEvaluateRecy.setHasFixedSize(true);
        mEvaluateRecy.setNestedScrollingEnabled(false);

        mEvaluateAdapter = new EvaluateAdapter(R.layout.item_evaluate, mData, this);
        mEvaluateRecy.setAdapter(mEvaluateAdapter);

        if(mRxPermissions == null){
            mRxPermissions = new RxPermissions(this);
        }

        mRxPermissions
                .request(Manifest.permission.READ_PHONE_STATE)
                .subscribe(aBoolean -> {
                    if(aBoolean){
                        mSerialNumber = getSerialNumber();
                        mEvaluateSerialnumber.setText(U.connectString("本机序列号为: ",mSerialNumber));
                    }else{
                        U.getSlectDialog(this, "温馨提示",
                                "您已经拒绝了权限,请在设置-应用管理中打开权限",
                                "取消", "打开", new Listener.OnNormalAlertDialogChooseClickListener() {
                            @Override
                            public void onLeft() {

                            }

                            @Override
                            public void onRight() {
                                Intent intent = new Intent();
                                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                Uri uri = Uri.fromParts("package", EvaluateActivity.this.getPackageName(), null);
                                intent.setData(uri);
                                startActivity(intent);
                            }
                        }).show();
                    }
                });
    }

    @Override
    protected void initData() {
        super.initData();

        InputStreamReader isr = null;
        try {
            isr = new InputStreamReader(getAssets().open("evaluate.json"),"UTF-8");
            BufferedReader br = new BufferedReader(isr);
            String line;
            StringBuilder builder = new StringBuilder();
            while((line = br.readLine()) != null){
                builder.append(line);
            }
            br.close();
            isr.close();

            Type type = new TypeToken<List<EvaluateBean>>() {
            }.getType();
            mJson = builder.toString();
            List<EvaluateBean> list = new Gson().fromJson(mJson, type);
            mData.addAll(list);
            mEvaluateAdapter.notifyDataSetChanged();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void commitSuccess(HttpWrapper<String> wrapper) {
        if(Constant.SUCCESS_CODE.equals(wrapper.code)){
            startActivity(new Intent(this, SellActivity.class));
            finish();
        }else{
            showMessage(wrapper.info);
        }
    }

    @Override
    protected void initListener() {
        super.initListener();

        mEvaluateBtnCommit.setOnClickListener(v -> {
            int sizeI = mData.size();
            list:
            for (int i = 0; i < sizeI; i++) {
                EvaluateBean evaluateBean = mData.get(i);
                final int position = i;
                List<EvaluateBean.ListBean> list = evaluateBean.getList();
                int sizeJ = list.size();
                params:
                for (int j = 0; j < sizeJ; j++) {
                    EvaluateBean.ListBean listBean = list.get(j);
                    if (listBean.isCheck()) {

                        break params;
                    }

                    /**
                     * 如果是最后一个item 则返回
                     */
                    if (j == sizeJ - 1) {
                        U.getSingleDialog(this, "提示",
                                U.connectString("请选择", evaluateBean.getName()),
                                "确定", () -> {
                                    mNoPosition = position;
                                }).show();
                        return;
                    }
                }
            }

            //没有问题
            mPresenter.commitPhoneInfo(getUserId(), Constant.PLATFORM, mSerialNumber, AppCenter.mGson.toJson(mData));
        });

    }

    /**
     * 得到序列号
     * @return
     */
    @SuppressLint("MissingPermission")
    private String getSerialNumber() {

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            return Build.getSerial();
        }

        String serial = null;

        try {

            Class<?> c = Class.forName("android.os.SystemProperties");

            Method get = c.getMethod("get", String.class);

            serial = (String) get.invoke(c, "ro.serialno");

        } catch (Exception e) {

            e.printStackTrace();

        }

        return serial;

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_evaluate;
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

}
